#!/bin/bash
set -e

SCRIPT_PATH="$(readlink -f ${BASH_SOURCE[0]})"
SCRIPT_DIR="$(dirname ${SCRIPT_PATH})"

REF_DIR=${SCRIPT_DIR}/ref
if [ ! -d "${REF_DIR}" ]; then
  echo "Reference directory ${REF_DIR} does not exist. Please create it."
  exit 1
fi

MARKDOWN_PART_DIR=${SCRIPT_DIR}/parts
MARKDOWN_PARTS=(
  "${MARKDOWN_PART_DIR}/bg.md"
  "${MARKDOWN_PART_DIR}/req.md"
  "${MARKDOWN_PART_DIR}/overall-design.md"
  "${MARKDOWN_PART_DIR}/detailed.md"
  "${MARKDOWN_PART_DIR}/db.md"
  "${MARKDOWN_PART_DIR}/impl.md"
  "${MARKDOWN_PART_DIR}/test.md"
  "${MARKDOWN_PART_DIR}/test-sheet.md"
  "${MARKDOWN_PART_DIR}/feel.md"
)

if [ ! -f "${INPUT}" ]; then
  echo "Input file ${INPUT} does not exist"
  DEFAULT_INPUT=report.md
  echo "Using default input file ${DEFAULT_INPUT}"
  echo > ${DEFAULT_INPUT}
  for part in "${MARKDOWN_PARTS[@]}"; do
    if [ -f "${part}" ]; then
      echo "Adding part: ${part}"
      cat "${part}" >> ${DEFAULT_INPUT}
      echo "" >> ${DEFAULT_INPUT}
    else
      echo "Part file ${part} does not exist." 1>&2
      exit 1
    fi
  done
  INPUT=${DEFAULT_INPUT}
  INTERMEDIATE=report.trim.md
  OUT=final-report.docx
else
  mkdir -p temp
  INTERMEDIATE=${INPUT%.md}.trim.md
  OUT=${SCRIPT_DIR}/${INPUT%.md}.docx
fi

echo "Using input file: ${INPUT}"
echo "Using intermediate file: ${INTERMEDIATE}"
echo "Using output file: ${OUT}"

python3 trim.py ${INPUT} $INTERMEDIATE
echo "Trimmed. Converting to docx..."
pandoc $INTERMEDIATE \
  --from markdown \
  --to docx \
  --output $OUT \
  --reference-doc=${REF_DIR}/template.docx \
  --filter pandoc-plantuml \
  --filter mermaid-filter \
  --lua-filter ${REF_DIR}/adjust-format.lua
  
if [ "${TEMP:1}" = "0" ]; then
  rm -f $INTERMEDIATE
  echo "Removed intermediate file: $INTERMEDIATE"
fi